package com.CmJava.servlet.executionChain.handlerMethodMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class AbstractHandlerMethodMapping {
    //路径和方法的映射存放位置
    private  AbstractHandlerMethodMapping.MappingRegistry mappingRegistry = new AbstractHandlerMethodMapping.MappingRegistry();

    public MappingRegistry getMappingRegistry() {
        return mappingRegistry;
    }

    public HandlerMethod getHandlerInternal(HttpServletRequest request) throws Exception{
        String lookupPath = request.getRequestURI();
        HandlerMethod handlerMethod = this.lookupHandlerMethod(lookupPath, request);
        return handlerMethod;
    }

    private HandlerMethod lookupHandlerMethod(String lookupPath, HttpServletRequest request) {
        List<Match> matches = new ArrayList();
        this.addMatchingMappings(lookupPath, matches, request);
        return matches.get(0).handlerMethod;
    }

    private void addMatchingMappings(String lookupPath, List<Match> matches, HttpServletRequest request) {
        matches.add(new Match(lookupPath,(HandlerMethod)this.mappingRegistry.getMappings().get(lookupPath)));
    }

    private class Match {
        private final String mapping;
        private final HandlerMethod handlerMethod;

        public Match(String mapping, HandlerMethod handlerMethod) {
            this.mapping = mapping;
            this.handlerMethod = handlerMethod;
        }

        public String getMapping() {
            return mapping;
        }

        public HandlerMethod getHandlerMethod() {
            return handlerMethod;
        }

        public String toString() {
            return this.mapping.toString();
        }
    }
    public class MappingRegistry {
        private final Map<String, HandlerMethod> mappingLookup = new LinkedHashMap();

        MappingRegistry() {
        }

        public Map<String, HandlerMethod> getMappings() {
            return this.mappingLookup;
        }
    }
}
